package com.vedana.bankmobile;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

/**
 * Activity that authentifies the user against the BankMobile server.
 * Fake login for the moment.
 * 
 * @author Didier MOISE
 */
public class LoginActivity extends Activity {
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		
		

		// load up the layout
		setContentView(R.layout.login);

		// get the button resource in the xml file and assign it to a local
		// variable of type Button
		Button launch = (Button) findViewById(R.id.login_button);

		// this is the action listener
		launch.setOnClickListener(new OnClickListener() {
			public void onClick(View viewParam) {
				// this gets the resources in the xml file and assigns it to a
				// local variable of type EditText
				EditText usernameEditText = (EditText) findViewById(R.id.txt_username);
				EditText passwordEditText = (EditText) findViewById(R.id.txt_password);

				// the getText() gets the current value of the text box
				// the toString() converts the value to String data type
				// then assigns it to a variable of type String
				String sUserName = usernameEditText.getText().toString();
				@SuppressWarnings("unused")
				String sPassword = passwordEditText.getText().toString();

				// this just catches the error if the program cant locate the
				// GUI stuff
				if (usernameEditText == null || passwordEditText == null) {
					// showAlert("Crap!",
					// "Couldn't find the 'txt_username' or 'txt_password' "
					// + "EditView in main.xml", "Oh shit!", false);
				} else {
					Intent intent = new Intent();
					intent.putExtra("userid", sUserName);

					storeLogin(sUserName, sPassword);
					
					quit(true, intent);
				}
			}
		}

		);
	}

	/**
	 * Quit login activity
	 * @param success true if successful
	 * @param i Returned Intent
	 */
	private void quit(boolean success, Intent i) {
		setResult((success) ? -1 : 0, i);
		finish();
	}
	
	/**
	 * Store user/password in preference file
	 * 
	 * @param user Username
	 * @param pwd Password
	 */
	private void storeLogin(String user, String pwd) {
		getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE)
        .edit()
        .putString(Constants.PREF_USERNAME, user)
        .putString(Constants.PREF_PASSWORD, pwd)
        .commit();		
	}
}
